﻿using Bigway.Common.Extensions;
using Bigway.Common.Interfaces;
using FluentValidation;

namespace Bigway.Common.Validations;

public class HasStartEndDatesValidator<T> : AbstractValidator<T>
    where T : IHasStartEndDates
{
    public HasStartEndDatesValidator(int minimalDurationInDays, bool isCreation)
    {
        if (isCreation)
        {
            RuleFor(x => x.StartDate)
                .Must(x => x >= DateOnlyExtensions.Today())
                .WithErrorCode("The start date cannot be in the past")
                .WithMessage("起始日期不能在过去");

            RuleFor(x => x.EndDate)
                .Must(x => x >= DateOnlyExtensions.Today())
                .WithErrorCode("The end date cannot be in the past")
                .WithMessage("结束日期不能在过去");
        }

        RuleFor(x => new { x.StartDate, x.EndDate })
            .Must(dates =>
            {
                if (dates.StartDate >= dates.EndDate)
                    return false;
                var durationInDays = dates.EndDate.GetDurationInDays(dates.StartDate);
                return durationInDays >= minimalDurationInDays;
            })
            .WithErrorCode($"The end date must be at least {minimalDurationInDays} days later than start date")
            .WithMessage($"结束日期必须在起始日期至少{minimalDurationInDays}天之后");
    }
}